//
//  EFAPjtResultsTVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/24.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAPjtResultsTVC.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <UIScrollView+EmptyDataSet.h>

@interface EFAPjtResultsTVC ()<AMapSearchDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (nonatomic, strong) AMapSearchAPI *search;
@property (strong, nonatomic) NSMutableArray<AMapPOI *> *searchPoiArray;
@property (strong, nonatomic) NSMutableArray<AMapTip *> *tipArray;
@end

static NSString *const kReuseCellId = @"UITableViewCell";

@implementation EFAPjtResultsTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self initSubViews];
}

- (void)initSubViews {
    self.tableView.tableFooterView = [UIView new];
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    if (@available(iOS 11.0, *)) { // 这里并不是布局的问题，仅仅是为了适配mjrefresh的下拉动画效果
        if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//            CGFloat statusHeight = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
//            CGFloat navHeight = CGRectGetHeight(self.navigationController.navigationBar.frame);
//            CGFloat tabHeight = CGRectGetHeight(self.tabBarController.tabBar.frame);
//            UIEdgeInsets edgeInsets = self.hidesBottomBarWhenPushed ? UIEdgeInsetsMake(statusHeight + navHeight, 0, 0, 0) : UIEdgeInsetsMake(statusHeight + navHeight, 0, tabHeight, 0);
//            self.tableView.contentInset = edgeInsets;
//            self.tableView.scrollIndicatorInsets = edgeInsets;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有搜到结果" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchPoiArray.count;
//    return self.tipArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kReuseCellId];
    }
    if (indexPath.row < self.searchPoiArray.count) {
        AMapPOI *poi = self.searchPoiArray[indexPath.row];
        cell.textLabel.text = poi.name;
        cell.detailTextLabel.text = poi.address;
    }
//    if (indexPath.row < self.tipArray.count) {
//        AMapTip *tip = self.tipArray[indexPath.row];
//        cell.textLabel.text = tip.name;
//        cell.detailTextLabel.text = [NSString stringWithFormat:@"(%@)(%.6f, %.6f)%@", tip.uid, tip.location.latitude, tip.location.longitude, tip.address];
//    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.searchPoiArray.count) {
        AMapPOI *poi = self.searchPoiArray[indexPath.row];
        if ([self.delegate respondsToSelector:@selector(resultsDidSelectPoint:)]) {
            [self.delegate resultsDidSelectPoint:poi];
        }
    }
}

#pragma mark - AMapSearchDelegate
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    NSLog(@"POI搜索结果返回: %ld", (unsigned long)response.pois.count);
//    NSLog(@"POI搜索推荐: %@, %@", response.suggestion.cities, response.suggestion.keywords);
    [self.searchPoiArray removeAllObjects];
    [self.searchPoiArray addObjectsFromArray:response.pois];
    [self.tableView reloadData];
}

- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response {
    NSLog(@"tips搜索结果返回：%ld", (unsigned long)response.count);
    [self.tipArray removeAllObjects];
    [self.tipArray addObjectsFromArray:response.tips];
    [self.tableView reloadData];
}

#pragma mark - event responds
- (void)refreshNewData {
    [self searchPoiWithKeywords:self.keywords];
//    [self searchTipsWithKeywords:self.keywords];
}

#pragma mark - private methods
- (void)searchPoiWithKeywords:(NSString *)keywords {
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    
    request.keywords = keywords;
//    request.requireExtension = YES;
//    request.requireSubPOIs = YES;
    request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    
    [self.search AMapPOIKeywordsSearch:request];
}

- (void)searchTipsWithKeywords:(NSString *)keywords {
    AMapInputTipsSearchRequest *request = [[AMapInputTipsSearchRequest alloc] init];
    
    request.keywords = keywords;
    
    [self.search AMapInputTipsSearch:request];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - gettes and setters
- (AMapSearchAPI *)search {
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}

- (NSMutableArray<AMapPOI *> *)searchPoiArray {
    if (!_searchPoiArray) {
        _searchPoiArray = [NSMutableArray array];
    }
    return _searchPoiArray;
}
- (NSMutableArray<AMapTip *> *)tipArray {
    if (!_tipArray) {
        _tipArray = [NSMutableArray array];
    }
    return _tipArray;
}

@end
